package com.um.springboot.starter.config;

import lombok.extern.slf4j.Slf4j;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 读取系统的SQL XML文件，存储需要执行的SQL
 * @author 邓南辉
 *
 */
@Slf4j
public class SystemSQL {

	private SystemSQL(){}
	
	
	
	private static SystemSQL _instance;
	private Map<String,String> sqlConfig = new Hashtable<String,String>();
	private String appName = "";
	public static SystemSQL getInstance(){
		if (_instance == null) {
			_instance = new SystemSQL();
		}
		return _instance;
	}
	
	/**
	 * 根据代号获得信息说明
	 */
	public String getSystemSQL(String key){
		return sqlConfig.get(this.appName+"."+key);
	}
	
	/**
	 * 读取系统配置信息
	 */
	public void initSystemSQL(String appName){
		this.appName = appName;

		try {
			ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
			Resource[] resources = resolver.getResources("classpath*:sql/*.xml");
			// 排序，方便服务重新模块内的sql
			List<Resource> resourcesList = Arrays.stream(resources).sorted((r1, r2) -> {
				if (r1 instanceof UrlResource && r2 instanceof FileSystemResource) {
					return 1;
				} else if (r2 instanceof UrlResource && r1 instanceof FileSystemResource) {
					return -1;
				} else {
					return 0;
				}
			}).collect(Collectors.toList());
			for (Resource resource : resourcesList) {
				log.debug(resource.getFilename() + "开始初始化...");
				try {
					parseSQLXML(appName, resource.getInputStream());
				} catch (Exception ex) {
					log.error("加载文件:" + resource.getFilename() + "失败，原因：" + ex.getMessage());
					continue;
				}
				log.debug(resource.getFilename() + "已加载完毕...");
			}

			log.info("UM SQL inited");

		}catch (Exception ex){
			log.error("初始化SQL出错：", ex);
		}
	}
	
	/**
	 * 加载XML文件中的SQL语句
	 * @param in 文件流对象
	 */
	@SuppressWarnings({"rawtypes" })
	private void parseSQLXML(String appName,InputStream in) throws FileNotFoundException,IOException,JDOMException{
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(in);
		Element root = doc.getRootElement();
		List list = root.getChildren();
		Iterator it = list.iterator();
		while (it.hasNext()) {
			Element e = (Element) it.next();
			String key = appName+"."+e.getAttributeValue("name");
			String value = e.getText();
			if(sqlConfig.containsKey(key)){
				log.warn("SQL Name属性"+key+"存在多条记录！");
				continue;
			}
			sqlConfig.put(key, value);
		}
		in.close();
	}
	
}
